<template>
  <div class="app-container">
    <div class="search-container">
      <!-- <el-form :model="queueSearchParams" :inline="true">
        <el-form-item label="当前站点" prop="mixingStationCode">
          <el-select
            v-model="queueSearchParams.mixingStationCode"
            class="station-select"
            placeholder="当前站点"
            @change="handleStationChange"
          >
            <el-option v-for="item in stationList" :key="item.id" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
      </el-form> -->
      <el-form ref="orderQueryFormRef" :model="orderQueryParams" :inline="true">
        <el-form-item label="当前站点">
          <el-select
            v-model="queueSearchParams.mixingStationCode"
            class="station-select"
            placeholder="当前站点"
            @change="handleStationChange"
          >
            <el-option v-for="item in stationList" :key="item.id" :label="item.name" :value="item.number" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号" prop="waybillCodeFuzzy" class="w-[220px]">
          <el-input v-model="orderQueryParams.waybillCodeFuzzy" placeholder="订单编号" clearable @keyup.enter="handleOrderQuery" />
        </el-form-item>
        <el-form-item label="客户名称" prop="customerNameFuzzy" class="w-[220px]">
          <el-input v-model="orderQueryParams.customerNameFuzzy" placeholder="客户名称" clearable @keyup.enter="handleOrderQuery" />
        </el-form-item>
        <el-form-item label="送货地址" prop="actualDeliveryAddressFuzzy" class="w-[220px]">
          <el-input
            v-model="orderQueryParams.actualDeliveryAddressFuzzy"
            placeholder="送货地址"
            clearable
            @keyup.enter="handleOrderQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" plain @click="handleOrderQuery">
            <template #icon><ep-Search /></template>
            搜索
          </el-button>
          <el-button type="primary" plain @click="handleRest">
            <template #icon><ep-Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-auto-h="{ bottom: 20 }" class="flex">
      <el-card class="w-[560px] shrink-0">
        <div class="text-center font-bold pb-[20px]">车辆队列</div>
        <div class="mb-[12px]">
          <el-button
            :type="queueSearchParams.status === 1 ? 'primary' : 'default'"
            :plain="queueSearchParams.status !== 1"
            round
            @click="handleStatusClick(1)"
          >
            排队中
          </el-button>
          <el-button
            :type="queueSearchParams.status === 2 ? 'primary' : 'default'"
            :plain="queueSearchParams.status !== 2"
            round
            @click="handleStatusClick(2)"
          >
            装货中
          </el-button>
        </div>
        <el-space v-if="queueSearchParams.status === 1" class="mb-6" wrap>
          <el-button type="primary" plain :disabled="moveFreezing" @click="handleMoveClick(MoveType.MOVE_UP)">上移</el-button>
          <el-button type="primary" plain :disabled="moveFreezing" @click="handleMoveClick(MoveType.MOVE_DOWN)">下移</el-button>
          <el-button type="primary" plain :disabled="moveFreezing" @click="handleMoveClick(MoveType.MOVE_TOP)">置顶</el-button>
          <el-button type="primary" plain :disabled="moveFreezing" @click="handleMoveClick(MoveType.MOVE_BOTTOM)">置底</el-button>
          <el-button type="danger" plain :disabled="moveFreezing" @click="handleCancel">取消排队</el-button>
          <el-button type="primary" @click="handleAddQueue">添加车辆</el-button>
        </el-space>
        <el-table v-loading="loading" v-auto-h="{ bottom: 30 }" :data="tableData" border highlight-current-row row-key="id">
          <el-table-column v-if="queueSearchParams.status === 1" width="55">
            <template #default="{ row }">
              <el-checkbox v-model="row.checked" @change="val => handleTableSelect(val, row)" />
            </template>
          </el-table-column>
          <el-table-column label="排号" width="80" align="center" prop="sortOrder" />
          <el-table-column v-if="queueSearchParams.status === 2" label="装料口" width="80" align="center" prop="outlet" />
          <el-table-column label="车牌号码" min-width="120" align="center" prop="carNumber" />
          <el-table-column label="搅拌车号" min-width="120" align="center" prop="carCode" />
          <el-table-column label="核载重量" width="100" align="center" prop="ratedVolume" />
          <!-- notice 只有装货中可以编辑 -->
          <el-table-column v-if="queueSearchParams.status === 2" align="center" label="操作" width="100">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card class="pt-[8px] ml-[8px] grow">
        <div ref="scrollEl" v-infinite-scroll="onloadData" v-auto-h="{ bottom: 20 }" :infinite-scroll-disabled="isDone">
          <div v-for="(item, i) in orderTableData" :key="item.id" class="p-[6px] rounded-[8px] mb-4 bg-white right-panel">
            <el-descriptions :column="5" border size="small">
              <el-descriptions-item label="订单编号">
                <el-link type="primary" @click="handleOrderCodeClick(item.id)">{{ item.waybillCode }}</el-link>
              </el-descriptions-item>
              <el-descriptions-item label="客户名称">{{ item.customerName }}</el-descriptions-item>
              <el-descriptions-item label="工程名称">{{ item.engineeringName }}</el-descriptions-item>
              <el-descriptions-item label="施工部位">{{ item.buildPlace }}</el-descriptions-item>
              <el-descriptions-item label="送货地址">{{ item.actualDeliveryAddress }}</el-descriptions-item>

              <el-descriptions-item label="强度等级">{{ item.concreteStrengthGrade }}</el-descriptions-item>
              <el-descriptions-item label="特殊要求">{{ item.specialRequirements }}</el-descriptions-item>
              <el-descriptions-item label="卸料方式">{{ item.unloadWay }}</el-descriptions-item>
              <el-descriptions-item label="塌落度">{{ item.concreteSlump }}</el-descriptions-item>
              <el-descriptions-item label="订货量 / 已送量">{{ item.reserveVolume + ' / ' + item.deliveredVolume }}</el-descriptions-item>
            </el-descriptions>

            <div class="h-[60px] mt-10 bg-white text-[12px] flex">
              <div class="grow flex">
                <div class="w-[90px]">
                  <div class="text-black leading-[30px] pl-30 pr-10">去程车辆</div>
                  <div class="text-black leading-[30px] pl-30 pr-10">回程车辆</div>
                </div>
                <div class="grow relative">
                  <!-- 分割线 -->
                  <svg class="svg-line absolute top-[20px]" :viewBox="svgViewBox">
                    <path :d="svgPath" />
                  </svg>

                  <!-- 去程 -->
                  <div class="flex h-1/2 justify-around">
                    <el-tooltip v-for="car in item.enhanceOutBoundCarList" :key="car.carNumber" placement="top" popper-class="popper">
                      <template #content>
                        <div>{{ car.carCode + ' - ' + car.carNumber }}</div>
                        <div>预计送达：{{ car.arriveTime }}</div>
                      </template>
                      <template #default>
                        <div class="inline cursor-pointer" :style="progressCarStyle(car)">
                          <svg
                            class="mx-[2px] car"
                            :class="{ offline: car.online === 0 || !car.gpsTime, warning: car.expStatus === 2 }"
                            width="30"
                            height="30"
                            @click="handleCarClick(car)"
                          >
                            <use xlink:href="#truck"></use>
                          </svg>
                        </div>
                      </template>
                    </el-tooltip>
                  </div>

                  <div class="flex h-1/2 justify-around">
                    <el-tooltip v-for="car in item.enhanceReturnCarList" :key="car.carNumber" placement="top" popper-class="popper">
                      <template #content>
                        <div>{{ car.carCode + ' - ' + car.carNumber }}</div>
                        <div>预计到达：{{ car.arriveTime }}</div>
                      </template>

                      <template #default>
                        <div class="inline cursor-pointer" :style="progressCarStyle(car, true)">
                          <svg
                            class="mx-[2px] car reverse"
                            :class="{ offline: car.online === 0 || !car.gpsTime, warning: car.expStatus === 2 }"
                            width="30"
                            height="30"
                            @click="handleCarClick(car)"
                          >
                            <use xlink:href="#truck"></use>
                          </svg>
                        </div>
                      </template>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              <div class="text-black w-[160px] pl-4">
                <el-tooltip :content="item.inDeliveryCarList" placement="top-start" :disabled="!item.inDeliveryNum">
                  <div>送货中：{{ item.inDeliveryNum || 0 }}</div>
                </el-tooltip>

                <el-tooltip :content="item.waitingCarList" placement="top-start" :disabled="!item.waitingNum">
                  <div>等待中：{{ item.waitingNum || 0 }}</div>
                </el-tooltip>

                <el-tooltip :content="item.unloadingCarList" placement="top-start" :disabled="!item.unloadingNum">
                  <div>卸货中：{{ item.unloadingNum || 0 }}</div>
                </el-tooltip>
              </div>
            </div>

            <el-descriptions border size="small">
              <el-descriptions-item label="发车顺序" label-class-name="w-[80px]">
                <div
                  v-for="car in item.departureOrder ? item.departureOrder.split(',') : []"
                  :key="car"
                  class="inline-block px-[6px] mr-[4px] rounded-[4px] bg-white car-outline"
                >
                  {{ car }}
                </div>
              </el-descriptions-item>
            </el-descriptions>

            <el-divider v-if="i + 1 !== orderTableData.length" />
          </div>
          <div v-if="orderTableLoading" class="text-center leading-[40px] text-[14px] hold-text">加载中...</div>
          <div v-else-if="orderTableData.length === 0" class="text-center leading-[40px] text-[14px] hold-text">暂无数据</div>
          <div v-else-if="isDone && orderQueryParams.nowPage > 1" class="text-center leading-[40px] text-[14px] hold-text">没有更多了</div>
        </div>
      </el-card>
    </div>
    <OrderDetail :id="detailId" v-model:visible="detailVisible" />
    <WaybillDetail :id="expWaybillId" v-model:visible="expDialogVisible" />
    <!-- 添加车辆 -->
    <el-dialog
      v-model="addCarVisible"
      width="1200px"
      title="添加排队车辆"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <div class="search-container">
        <el-form :model="addCarSearchParams" :rules="editFormRules" label-width="100px" inline>
          <el-form-item label="车牌号码" prop="orderCodeFuzzy">
            <el-input v-model="addCarSearchParams.carNumberFuzzy" placeholder="车牌号码" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item label="搅拌车号" prop="mixingCarCodeFuzzy">
            <el-input v-model="addCarSearchParams.mixingCarCodeFuzzy" placeholder="搅拌车号" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <template #icon><ep-Search /></template>
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="addCarLoading" height="400" :data="carTableData" border highlight-current-row>
        <el-table-column width="55">
          <template #default="{ row }">
            <el-checkbox v-model="row.checked" @change="val => handleAddCarSelect(val, row)" />
          </template>
        </el-table-column>
        <el-table-column label="车牌号码" align="center" prop="carNumber" />
        <el-table-column label="搅拌车号" align="center" prop="mixingCarCode" />
        <el-table-column label="核载重量" align="center" prop="weightLimit" />
        <el-table-column label="上线状态" align="center">
          <template #default="{ row }">
            {{ row.onlineStatus === 0 ? '离线' : '在线' }}
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-model:page="addCarSearchParams.nowPage"
        v-model:pagesize="addCarSearchParams.pageSize"
        :total="addCarTotal"
        @pagination="handlePaginationChange"
      />
      <template #footer>
        <el-button @click="addCarVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleAddCommitClick">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑装货车辆 -->
    <el-dialog
      v-model="editDialogVisible"
      width="600px"
      title="编辑排队信息 "
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <el-form ref="editFormRef" :model="editFormModel" :rules="editFormRules" label-width="100px">
        <el-form-item label="装料口" prop="outlet">
          <!-- outletList -->
          <el-select v-model="editFormModel.outlet" placeholder="装料口">
            <el-option v-for="item in outletList" :key="item.code" :label="item.outlet" :value="item.code" />
          </el-select>
          <!-- <el-input v-model="editFormModel.outlet" placeholder="装料口" /> -->
        </el-form-item>

        <el-form-item label=" 装货车辆" prop="carNumber">
          <el-select v-model="editFormModel.carNumber" placeholder="装货车辆">
            <el-option
              v-for="item in editableVehicles"
              :key="item.id"
              :label="item.carCode + '-' + item.carNumber"
              :value="item.carNumber"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEditCommitClick">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import type { CheckboxValueType } from 'element-plus'

import { useRequest } from '@/hooks/useRequest'
// 获取搅拌站权限
import { getMixingStationList, type MixingStationData } from '@/api/customer/customer'

import { MoveType, getCarAddTableData, addCarRequest } from '@/api/signboard/index'
import type { CarQueryParams, AddCarSearchParams, AddCar } from '@/api/signboard/index'
import { useCarQueue, useEdit, useOrder } from './index'

import Storage from '@/utils/Storage'
import { DEFAULT_MIXING_STATION_ID_KEY } from '@/utils/constant'

import OrderDetail from '@/views/order/detail.vue'
import WaybillDetail from '@/views/waybill/detail.vue'

type AddCarRow = AddCar & { checked?: boolean }

const queueSearchParams = reactive<CarQueryParams>({
  status: 1, // 车辆状态: 1排队中 2装货中
  mixingStationCode: '' // 	搅拌站编码
})

const { tableData, handleSearchCar, loading, handleStatusClick, handleTableSelect, moveFreezing, handleMoveClick, handleCancel } =
  useCarQueue(queueSearchParams)

// 编辑
const {
  editDialogVisible,
  editFormRef,
  editFormModel,
  editFormRules,
  editableVehicles,
  editLoading,
  outletList,
  handleEdit,
  handleEditCommitClick
} = useEdit(queueSearchParams, handleSearchCar)

const {
  orderQueryFormRef,
  orderQueryParams,
  orderTableLoading,
  orderTableData,
  isDone,
  handleOrderQuery,
  handleRest,
  onloadData,
  expDialogVisible,
  expWaybillId,
  handleCarClick,
  progressCarStyle
} = useOrder(queueSearchParams)

const refreshAllData = () => {
  handleSearchCar()
  handleOrderQuery()
}

const handleStationChange = (number: string) => {
  const mixingStation = stationList.value.find(item => item.number === number)

  if (mixingStation) {
    Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, mixingStation.id)
    // 刷新所有数据
    refreshAllData()
  }
}

const { data: stationRes } = useRequest(getMixingStationList, {
  onSuccess({ result }) {
    if (result && result.length) {
      let defaultMixingStation: MixingStationData = null
      const defaultMixingStationId = Storage.getStorage(DEFAULT_MIXING_STATION_ID_KEY)

      // 先从本地缓存匹配搅拌站数据；如果能找到数据，则说明该用户有本地缓存搅拌站的权限
      if (defaultMixingStationId) {
        defaultMixingStation = result.find(item => item.id === defaultMixingStationId)
      }

      // 如果无缓存或者无法匹配到数据；则默认取第一个数据并重新设置缓存
      if (!defaultMixingStation) {
        defaultMixingStation = result[0]
        Storage.setStorage(DEFAULT_MIXING_STATION_ID_KEY, defaultMixingStation.id)
      }

      queueSearchParams.mixingStationCode = defaultMixingStation.number
      refreshAllData()
    }
  }
})

const stationList = computed(() => stationRes.value?.result || [])

// 新增车辆功能
const addCarVisible = ref(false)
const addCarSearchParams = reactive<AddCarSearchParams>({
  carNumberFuzzy: '',
  mixingCarCodeFuzzy: '',
  nowPage: 1,
  pageSize: 10,
  mixingStationNumber: ''
})
const addCarTotal = ref(0)
let selectedCar: AddCarRow = null
const handleAddCarSelect = (val: CheckboxValueType, row: AddCarRow) => {
  // 已选中清空选中
  selectedCar && (selectedCar.checked = false)
  // 选中值
  selectedCar = null
  if (val) {
    selectedCar = row
  }
}

const carTableData = ref<AddCarRow[]>([])
const { run: runAddCar, loading: addCarLoading } = useRequest(getCarAddTableData, {
  manual: true,
  onSuccess({ result }) {
    const { records, total: totalRes } = result
    addCarTotal.value = totalRes
    carTableData.value = records.map(row => ({
      ...row,
      checked: false
    }))
  }
})

const handleQuery = () => {
  addCarSearchParams.nowPage = 1
  runAddCar(addCarSearchParams)
}

const handlePaginationChange = (page: number, pageSize: number) => {
  addCarSearchParams.nowPage = page
  addCarSearchParams.pageSize = pageSize
  runAddCar(addCarSearchParams)
}
// 添加车辆，排队中可以添加
const handleAddQueue = () => {
  addCarSearchParams.mixingStationNumber = queueSearchParams.mixingStationCode
  addCarSearchParams.carNumberFuzzy = ''
  addCarSearchParams.pageSize = 10
  addCarTotal.value = 0
  selectedCar = null
  handleQuery()
  addCarVisible.value = true
}

const handleAddCommitClick = async () => {
  if (!selectedCar) ElMessage.error('请选择车辆')
  await addCarRequest({ onlineCarId: selectedCar.id })
  ElMessage.success('成功添加排队车辆')
  addCarVisible.value = false
  handleSearchCar() // 刷新排队车辆队列
}

const detailId = ref('')
const detailVisible = ref(false)
const handleOrderCodeClick = (id: string) => {
  detailId.value = id
  detailVisible.value = true
}

// resize 重绘 svg
const scrollEl = ref()
const viewBoxWidth = ref(800)
const svgPath = computed(() => `M20 18 L 0 10 L ${viewBoxWidth.value} 10 L ${viewBoxWidth.value - 20} 2`)
const svgViewBox = computed(() => `0 0 ${viewBoxWidth.value} 20`)
function svgCalc(width: number) {
  viewBoxWidth.value = width - 160 - 90
}

function observerCallback(entries) {
  const current = entries[0]
  const { target } = current
  const width = target.getBoundingClientRect().width
  svgCalc(width)
}
const observer = new ResizeObserver(observerCallback)

watch(scrollEl, el => {
  if (el) {
    observer.observe(el)
  }
})
</script>
<style lang="scss" scoped>
/*
.station-select.el-select {
  --el-select-width: 400px;
}
*/
.svg-line {
  fill: none;
  stroke: #409eff;
  stroke-linecap: round;
  stroke-linejoin: miter;
  stroke-width: 2;
}

.car {
  fill: var(--el-color-primary);
}

.reverse {
  transform: rotateY(180deg);
}

.warning {
  fill: var(--el-color-danger-dark-2);
}

.offline {
  fill: var(--el-color-info);
}

.idle {
  fill: var(--el-color-warning);
}

.popper {
  background-color: #409eff;
  color: #fff;
}

.table-card {
  box-shadow: inset 0 0px 4px 0 #d5d4d4;
}
.hold-text {
  color: var(--el-text-color-secondary);
}
.car-outline {
  box-shadow: 0 0 0 1px inset #0000001f;
}
@media only screen and (min-width: 1600px) {
  :deep(.right-panel) {
    width: 100%;
  }
}

@media only screen and (max-width: 1600px) {
  :deep(.right-panel) {
    width: 760px;
  }
}
</style>
